<template>
  <div class="container" :class="{'darkmode' : isDarkmode}">
    <!-- 左侧开始 -->
    <div class="left">
      <div class="left-top">
        <el-input
          style="width: 240px"
          size="large"
          placeholder="查询收藏记录"
          :suffix-icon="Search"
          v-model="inputValue"
          clearable
        />
      </div>
      <div class="left-bottom">
        <el-menu
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose"
          @select="handleSelect"
        >
          <el-sub-menu index="1">
            <template #title>
              <span>{{publiclyAccessibleBookmarks.name}}</span>
            </template>
            <el-menu-item @click="addCollectDir" :disabled="true" index="1-0"><el-icon><FolderAdd /></el-icon>新建收藏夹</el-menu-item>
            <el-menu-item v-for="s in publiclyAccessibleBookmarks.collectTwoDirVOList" :key="s.id" :index="'1-' + s.id"><el-icon><Folder /></el-icon>{{s.title}}</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="2" :disabled="disabled" @click="clickEncryptCollect">
            <template #title>
              <span>{{privacyFavorites.name}}</span>
            </template>
            <el-menu-item index="2-0" :disabled="true"><el-icon><FolderAdd /></el-icon>新建加密收藏夹</el-menu-item>
            <el-menu-item v-for="l in privacyFavorites.collectTwoDirVOList" :key="l.id" :index="'2-' + l.id"><el-icon><Folder /></el-icon>{{l.title}}</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>
    </div>
    <!-- 左侧结束 -->
    <!-- 右侧开始 -->
    <div class="right">
      <div class="right-top">
        <div class="right-top-title">收藏记录</div>
        <div class="right-top-clear">
          <el-icon><DeleteFilled /></el-icon>
          <span @click="handleClearAll" style="margin-left: 10px;">清空收藏</span>
        </div>
      </div>
      <div class="right-bottom">
        <el-card v-if="isViewDefault" style="max-width: 100%; margin: 20px 0px;">
          <div class="right-bottom-elcard-content">
            <div class="right-bottom-elcard-content-title">当前收藏夹暂时没有内容</div>
          </div>
        </el-card>
        <el-card v-else style="max-width: 100%; margin: 20px 0px;" v-for="c in collectContentList" :key="c.id">
          <img @click="handleSkip(c.url)" :src="c.cover" alt="封面">
          <div class="right-bottom-elcard-content">
            <!-- 后续可以考虑计算属性什么的，即这里需要对于长标题进行简化显示 -->
            <div @click="handleSkip(c.url)" class="right-bottom-elcard-content-title">{{c.title}}</div>
            <div class="right-bottom-elcard-content-control">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="移除对应收藏记录"
                @confirm="confirmEvent(c.id)"
                @cancel="cancelEvent"
              >
                <template #reference>
                  <el-icon :size="20" class="iconfont icon-gengduo"></el-icon>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <!-- 右侧结束 -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { type CollectContentItem, type CollectTwoDirItem, type CollectOneDirItem }from '@/types/collectInterface.ts';
import {collectApi} from '@/api/collect.js'
import {useRouter} from 'vue-router'

//### 定义数据 ###
const router = useRouter();
const disabled = ref(true);
const isDarkmode = ref(false);  //是否开启夜间模式
const inputValue = ref('');      //搜索框输入的值
const isViewDefault = ref(false); //是否显示默认
//公开收藏夹
const publiclyAccessibleBookmarks = reactive<CollectOneDirItem>({
  id:"1",
  name: "我的收藏夹",
  collectTwoDirVOList: [
    {
      id: "4",
      name: "默认收藏夹",
    },
    {
      id: "1",
      name: "程序员学习资料",
    }
  ]
})
//隐私收藏夹
const privacyFavorites = reactive<CollectOneDirItem>({
  id:"2",
  name: "加密收藏夹",
  collectTwoDirVOList: [
  ]
})
//对应收藏具体内容集合
const collectContentList = ref<CollectContentItem[]>([]);

//### 定义函数 ###
//页面初始化函数
const pageInitialization = async () => {
  const result = await collectApi.obtainTheCorrespondingDataThroughThePrimaryDirectoryId({"oneDirId": 1});
  if(result.code === 200) {
    Object.assign(publiclyAccessibleBookmarks, result.data.collectOneDirVO);
  }

  const collectData = await collectApi.getAllCollectContentByUserId();
  if(collectData.code === 200) {
    collectContentList.value = collectData.data.collectContentList;
  }else {
    isViewDefault.value = true;
  }
}

pageInitialization();

//点击对应收藏内容后的跳转
const handleSkip = (url:string) => {
  console.log("看看跳转地址", url)
  const [path, paramValue] = url.split("?");
  router.push({
    path: path,
    query: {
      articleId: paramValue
    }
  });
}

//对应气泡确定框的确定和取消方法
const confirmEvent = async (id:string) => {
  console.log('对应的id', id)
  const result = await collectApi.deleteASingleCollection({"id":id});
  if(result.code === 200) {
    const index = collectContentList.value.findIndex(c => c.id === id);
    if (index !== -1) {
      collectContentList.value.splice(index, 1); // 删除第一个匹配项
    }

    if(collectContentList.value.length < 1) { //删除完了，所以显示没有数据
      isViewDefault.value = true;
    }
  }
}
const cancelEvent = () => {
  console.log('cancel!')
}

//清空对应收藏记录
const handleClearAll = () => {
  ElMessageBox.confirm(
    '你确定清除所有收藏记录吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await collectApi.deleteAll();
      if(result.code === 200) {
        ElMessage({
          type: 'success',
          message: '清除成功',
        })
        isViewDefault.value = true;
        pageInitialization();
      }else {
        ElMessage({
          type: 'error',
          message: '清除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '清除操作取消或异常',
      })
    })  
}

//新建收藏夹
const addCollectDir = () => {
  console.log("点击了新建收藏夹")
}

//对应选中菜单后调用的方法，不算打开关闭
const handleSelect = async (index:string) => {
  console.log('当前选中的菜单项:', index);
  const i = index.indexOf('-');
  if(i !== -1) {
    const id = index.substring(i + 1);
    const result = await collectApi.getCollectContentBySecondLevelId({"id":id});
    console.log("看看截取的获取的结果", result)
    if(result.code === 200) {
      isViewDefault.value = false;
      collectContentList.value = result.data.collectContentList;
    }else {
      isViewDefault.value = true;
    }
  }
}

//菜单栏的回调函数
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

const clickEncryptCollect = () => {
  console.log('我被点了');
  if(disabled.value) {
    ElMessageBox.prompt('请输入解锁密码', '解锁弹窗', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      inputPattern:
        /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{16}$/,
      inputErrorMessage: '16位密码, 包含大小写字母、数字、特殊字符（!@#$%^&*）',
      inputType: "password"
    })
      .then(async ({ value }) => {
        disabled.value = false;
        const result = await collectApi.validatePassword({"enterPassword":value});
        console.log("验证密码的结果", result);
        if(result.code === 200) {
          ElMessage({
            type: 'success',
            message: `密码正确`,
          })
          privacyFavorites.collectTwoDirVOList = result.data.secondLevelCollectList;
        }else {
          ElMessage({
            type: 'warning',
            message: result.msg,
          })
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
  }
}

//### 监听方法 ###
watch(inputValue, async (newVal, oldVal) => {
  if(newVal === "") { //查看所有
    isViewDefault.value = false;
    pageInitialization();
  }else {
    const result = await collectApi.searchCollectByTitle({"title": oldVal});
    console.log("看看搜索结果", result);
    if(result.code === 200) {
      collectContentList.value = result.data.collectContentList;
    }else {
      isViewDefault.value = true;
    }
  }
});

//### 生命周期函数 ###
onMounted(() => {
  //夜间模式检查
  let darkmode = window.localStorage.getItem('tenSeekIsDarkmode');
  if(darkmode === 'true') {
    isDarkmode.value = true;
  }
})
</script>


<style scoped lang="scss">
.container {
  // background: antiquewhite;
  display: flex;
  height: 85vh;

  // margin: 10px 0px;

  .left {
    // background: red;
    flex: 1;
    padding: 10px;

    .left-top {
      margin-bottom: 10px;
      
      /* 搜索框 */
      ::v-deep .el-input__wrapper {
        background: var(--base-color);
      }

      /* 搜索框内部文字 */
      ::v-deep .el-input__inner {
        color: var(--text-color);
      }
    }

    .left-bottom {

      /* 整体菜单背景 */
      ::v-deep .el-menu {
        background: var(--base-color);
      }

      /* 对应一级菜单颜色 */
      ::v-deep .el-sub-menu__title {
        color: var(--text-color);
      }

      /* 对应二级菜单颜色 */
      ::v-deep .el-menu-item {
        color: var(--text-color);
      }

      /* 选中后菜单的颜色 */
      ::v-deep .is-active {
        color: #409EFF;
      }
    }

  }

  .right {
    // background: blue;
    flex: 9;
    overflow-x: auto;
    
    .right-top {
      display: flex;
      justify-content: space-between; /* 使子项在主轴上两端分布 */
      align-items: center;  /* 复轴居中 */
      margin: 10px 80px 0px;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
      border-radius: 4px;
      height: 30px;

      .right-top-title {
        // background: chartreuse;
        border-radius: 4px 0px 0px 4px;
        padding-left: 20px;
        font-weight: bold;
      }

      .right-top-clear {
        // background: chartreuse;
        border-radius: 0px 4px 4px 0px;
        display: flex;
        align-items: center;  /* 复轴居中 */
        padding-right: 20px;
      }
    }

    .right-bottom {
      display: grid;  /* 网格布局 */
      grid-template-columns: repeat(auto-fit, 240px); /* 子元素宽度 100px */
      justify-content: center; /* 整体居中 */
      gap: 15px; /* 子元素间距 */

      ::v-deep .el-card__body {
        padding: 0px;
      }

      .right-bottom-elcard-content {
        display: flex;
        justify-content: space-between;

        .right-bottom-elcard-content-title {
          margin-left: 5px;
        }

        .right-bottom-elcard-content-control {
          margin-top: 3px;
        }
      }

      img {
        width: 100%;
      }
    }
  }
}

</style>